package com.chaoyong.higo.wxapi;

import java.io.UnsupportedEncodingException;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.chaoyong.higo.activity.Login2Activity;
import com.chaoyong.higo.activity.LoginActivity;
import com.chaoyong.higo.activity.MainActivity;
import com.chaoyong.higo.base.BaseApp;
import com.chaoyong.higo.net.OApi;
import com.chaoyong.higo.utils.PrefUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler{

	private Bundle bundle;
	private Activity context;
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		context = this;
		BaseApp.iwxapi.handleIntent(getIntent(), this);
	}

	@Override
	public void onReq(BaseReq arg0) {
		
	}

	@Override
	public void onResp(BaseResp arg0) {
		// TODO Auto-generated method stub
		bundle=getIntent().getExtras();  
        SendAuth.Resp resp = new SendAuth.Resp( bundle);  
      //获取到code之后，需要调用接口获取到access_token  
         if (resp.errCode == BaseResp.ErrCode.ERR_OK) {  
              String code = resp.code;  
              //Toast.makeText(this, code, 1).show();
              // if(BaseApplication. isWxLogin){  
                    getToken(code);  
             /* } else{  
                    WXEntryActivity. this.finish();  
              } */ 
        } else{  
              WXEntryActivity. this.finish();  
        } 
	}

	private void getToken(String code) {
		// TODO Auto-generated method stub
		/*JSONObject json = new JSONObject();
		try {
			json.put("appid", "wxd13d827c27bcd2a9");
			json.put("secret", "3aabf2ee1010adf6a04bc4fde91ba22f");
			json.put("code", code);
			json.put("grant_type", "authorization_code");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		RequestParams params = new RequestParams();
		try {
			params.setBodyEntity(new StringEntity(json.toString(), "utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		HttpUtils utils = new HttpUtils();
		utils.send(HttpMethod.GET, "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxd13d827c27bcd2a9&secret=3aabf2ee1010adf6a04bc4fde91ba22f&code=" + code + "&grant_type=authorization_code", new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				// TODO Auto-generated method stub
				String result = arg0.result;
				//Toast.makeText(context, result, 1).show();
				try {
					JSONObject jo = new JSONObject(result);
					HttpUtils http = new HttpUtils();
					http.send(HttpMethod.GET, "https://api.weixin.qq.com/sns/userinfo?access_token=" + jo.getString("access_token") + "&openid=" + jo.getString("openid"), new RequestCallBack<String>() {

						@Override
						public void onFailure(HttpException arg0, String arg1) {
							// TODO Auto-generated method stub
							
						}

						@Override
						public void onSuccess(ResponseInfo<String> arg0) {
							// TODO Auto-generated method stub
							String userinfo = arg0.result;
							//Toast.makeText(context, userinfo, 1).show();
							final JSONObject jo;
							try {
								jo = new JSONObject(userinfo);
								//Toast.makeText(context, userinfo, 1).show();
								
								JSONObject json = new JSONObject();
								try {
									json.put("unionid", jo.getString("unionid"));
									json.put("nickname", jo.getString("nickname"));
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								RequestParams params = new RequestParams();
								try {
									params.setBodyEntity(new StringEntity(json.toString(), "utf-8"));
								} catch (UnsupportedEncodingException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								HttpUtils utils = new HttpUtils();
								utils.send(HttpMethod.POST, OApi.Public_wxLogin, params, new RequestCallBack<String>() {

									@Override
									public void onFailure(HttpException arg0, String arg1) {
										// TODO Auto-generated method stub
										
									}

									@Override
									public void onSuccess(ResponseInfo<String> arg0) {
										// TODO Auto-generated method stub
										String results = arg0.result;
										//Toast.makeText(context, results, 1).show();
										try {
											JSONObject jsonObject = new JSONObject(results);
											JSONObject data = jsonObject.getJSONObject("data");
											String uid = data.getString("uid");
											if(jsonObject.getInt("status") == 1){
												//Toast.makeText(context, "已经注册过了，可以直接登录了", 1).show();
												OApi.uid = uid;
												PrefUtils.setBoolean(context, "isLogin", true);
												PrefUtils.setString(context, "userId", uid);
												PrefUtils.setString(context, "userName", jo.getString("nickname"));
												startActivity(new Intent(context, MainActivity.class));
												context.finish();
											}
											if(jsonObject.getInt("status") == 2){
												//Toast.makeText(context, "没有注册过，去注册", 1).show();
												Intent intent = new Intent(context, Login2Activity.class);
												intent.putExtra("uid", uid);
												context.finish();
												startActivity(intent);
											}
										} catch (JSONException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								});
								
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					});
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}
	
}
